const config = require("../configs.js");

/**
 * @description  获取当前日期
 * @returns {string}
 */
const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
  const day = String(date.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
};

/**
 * @description  获取当前菜单   并重组为数组
 * @returns {string}
 */
const convertMenuStringToArray = () => {
  return config.menu?.split(/\s*\/\s*/);
};

/**
 * @description  处理树 数据
 * @returns {Array}
 */
const flatArrayToTree = (list) => {
  const result = [];
  const map = {};

  // 先构建一个id映射表
  list.forEach((item) => {
    map[item.id] = {
      ...item,
      disabled: item.state === "无效",
      children: [],
    };
  });

  // 然后根据parentid将子节点添加到父节点的children属性下
  list.forEach((item) => {
    if (item.parent !== "#") {
      map[item.parent].children.push(map[item.id]);
    } else {
      result.push(map[item.id]);
    }
  });

  return result;
};

/**
 * @description 递归查找菜单树中匹配的路径
 * @param {Array} menuTree - 树形菜单数据
 * @param {Array} pathArray - 要匹配的路径数组（如 ["成品品质管理", "成品不合格管理"]）
 * @param {number} currentIndex - 当前查找的路径索引（默认从 0 开始）
 * @returns {Object|null} 匹配的菜单节点，未找到返回 null
 */
const findMenuByPath = (menuTree, pathArray, currentIndex = 0) => {
  if (!menuTree || !pathArray || currentIndex >= pathArray.length) {
    return null;
  }

  const targetText = pathArray[currentIndex];
  const foundNode = menuTree.find((node) => node.text === targetText);

  if (!foundNode) {
    return null; // 当前层级未找到
  }

  // 如果是路径的最后一项，直接返回
  if (currentIndex === pathArray.length - 1) {
    return foundNode;
  }

  // 继续递归查找子节点
  return findMenuByPath(foundNode.children, pathArray, currentIndex + 1);
};

module.exports = {
  getCurrentDate,
  convertMenuStringToArray,
  flatArrayToTree,
  findMenuByPath,
};
